<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTimeRange" style="width: 360px">
        <el-date-picker v-model="orderTimeRange" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" show-summary :summary-method="summaryMethod">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="70" type="index" :index="indexMethod" />
      <el-table-column label="用户名" align="center">
        <template #default="scope">{{ pick(scope.row, ['userName','nickName','applyUserName','customerName']) }}</template>
      </el-table-column>
      <el-table-column label="门店" align="center">
        <template #default="scope">{{ scope.row.shopName }}</template>
      </el-table-column>
      <el-table-column label="绑定手机号" align="center">
        <template #default="scope">{{ scope.row.userPhone }}</template>
      </el-table-column>
      <el-table-column label="项目" align="center">
        <template #default="scope">{{ pick(scope.row, ['itemName','projectName']) }}</template>
      </el-table-column>
      <el-table-column label="订单编号" align="center">
        <template #default="scope">{{ pick(scope.row, ['orderCode','orderNo']) }}</template>
      </el-table-column>
      <el-table-column label="订单总金额" align="center">
        <template #default="scope">{{ scope.row.sumAmount ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="次卡抵扣" align="center">
        <template #default="scope">{{ scope.row.backPayment1 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="余额支付" align="center">
        <template #default="scope">{{ scope.row.payment1 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="账户剩余金额" align="center">
        <template #default="scope">{{ scope.row.backPayment2 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="产品账户支付" align="center">
        <template #default="scope">{{ scope.row.payment2 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="现金支付" align="center">
        <template #default="scope">{{ scope.row.payment3 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="银行卡支付" align="center">
        <template #default="scope">{{ scope.row.payment4 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="挂账支付" align="center">
        <template #default="scope">{{ scope.row.payment5 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="免账支付" align="center">
        <template #default="scope">{{ scope.row.payment6 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="微信支付" align="center">
        <template #default="scope">{{ scope.row.payment7 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="支付宝支付" align="center">
        <template #default="scope">{{ scope.row.payment8 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="大众点评抵扣" align="center">
        <template #default="scope">{{ scope.row.payment9 ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="卡支付金额" align="center">
        <template #default="scope">{{ scope.row.cardAmount ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" width="180">
        <template #default="scope">{{ parseTime(scope.row.createTime || scope.row.orderTime) }}</template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" width="180">
        <template #default="scope">{{ parseTime(scope.row.payTime) }}</template>
      </el-table-column>
      <el-table-column label="订单状态" align="center">
        <template #default="scope">{{ scope.row.orderStatus || scope.row.status }}</template>
      </el-table-column>
      <el-table-column label="备注信息" align="center">
        <template #default="scope">{{ scope.row.remark }}</template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="绑定手机号" prop="bindPhone">
          <div style="display:flex; gap:8px; width:100%">
            <el-input v-model="form.bindPhone" placeholder="请输入绑定手机号" maxlength="11" @input="onBindPhoneInput" />
            <el-button :loading="searchingUser" @click="handleSearchUser">查询用户</el-button>
          </div>
        </el-form-item>
        <el-form-item label="购买用户">
          <span>{{ form.purchaserName || '--' }}</span>
        </el-form-item>
        <el-form-item label="订单编号">
          <span>{{ form.orderCode || '--' }}</span>
        </el-form-item>

        <el-divider>消费项目</el-divider>
        <div style="display:flex; gap:8px; margin-bottom:8px;">
          <el-button type="primary" @click="addItemRow">添加</el-button>
          <el-button type="danger" @click="removeSelectedItems">删除</el-button>
        </div>
        <el-table :data="form.items" @selection-change="sel => (selectedItemRows = sel)" size="small" empty-text="暂无数据">
          <el-table-column type="selection" width="45" />
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="项目名称" min-width="180">
            <template #default="scope">
              <el-select v-model="scope.row.itemId" placeholder="请选择项目名称" filterable style="width: 100%" @change="val => onSelectItem(scope.row, val)">
                <el-option v-for="it in projectOptions" :key="it.value" :label="it.label" :value="it.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="scope">
              <span>{{ Number(scope.row.price || 0).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-button size="small" @click="decrement(scope.row, 'qty')" :disabled="!scope.row.qty || scope.row.qty <= 0">-</el-button>
                <el-input-number v-model="scope.row.qty" :min="0" :step="1" :controls="false" size="small" style="width: 60px; margin: 0 5px;" @change="calcTotals" />
                <el-button size="small" @click="increment(scope.row, 'qty')">+</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="次卡剩余" width="100">
            <template #default="scope">
              <span>{{ scope.row.cardRemain || 0 }}次</span>
            </template>
          </el-table-column>
          <el-table-column label="划卡次数" width="150">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-button size="small" @click="decrement(scope.row)" :disabled="!scope.row.cardTimes || scope.row.cardTimes <= 0">-</el-button>
                <el-input-number 
                  v-model="scope.row.cardTimes"
                  :min="0" 
                  :step="1" 
                  :max="scope.row.cardRemain || 0" 
                  :controls="false" 
                  size="small" 
                  style="width: 60px; margin: 0 5px;"
                  @change="(val) => handleCardTimesChange(scope.row, val)"
                />
                <el-button size="small" @click="increment(scope.row)" :disabled="scope.row.cardRemain === 0 || scope.row.cardTimes >= (scope.row.cardRemain || 0)">+</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="技师" min-width="120">
            <template #default="scope">
              <el-select 
                v-model="scope.row.technician" 
                placeholder="请选择技师" 
                filterable 
                clearable
                style="width: 100%"
                :loading="loadingTechnicians"
                :disabled="loadingTechnicians"
              >
                <el-option 
                  v-for="tech in technicianOptions" 
                  :key="tech.value" 
                  :label="tech.label" 
                  :value="tech.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="最终金额" width="140">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.finalAmount" 
                :min="0" 
                :precision="2" 
                :step="1"
                style="width: 100%"
                @change="() => updateItemFinalAmount(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>

        <el-divider>消费产品</el-divider>
        <div style="display:flex; gap:8px; margin-bottom:8px;">
          <el-button type="primary" @click="addProductRow">添加</el-button>
          <el-button type="danger" @click="removeSelectedProducts">删除</el-button>
        </div>
        <el-table :data="form.products" @selection-change="sel => (selectedProductRows = sel)" size="small" empty-text="暂无数据">
          <el-table-column type="selection" width="45" />
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="产品名称" min-width="180">
            <template #default="scope">
              <el-select v-model="scope.row.productId" placeholder="请选择产品名称" filterable style="width: 100%" @change="val => onSelectProduct(scope.row, val)">
                <el-option v-for="g in goodsOptions" :key="g.value" :label="g.label" :value="g.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="scope">
              <span>{{ Number(scope.row.price || 0).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-button size="small" @click="decrementQty(scope.row)" :disabled="!scope.row.qty || scope.row.qty <= 0">-</el-button>
                <el-input-number 
                  v-model="scope.row.qty" 
                  :min="0" 
                  :step="1" 
                  :controls="false" 
                  size="small" 
                  style="width: 60px; margin: 0 5px;" 
                  @change="() => updateProductAmount(scope.row)"
                />
                <el-button size="small" @click="incrementQty(scope.row)">+</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="方案" min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row.plan" placeholder="请输入方案" />
            </template>
          </el-table-column>
          <el-table-column label="最终金额" width="140">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.finalAmount" 
                :min="0" 
                :precision="2" 
                :step="1"
                style="width: 100%"
                @change="() => updateItemFinalAmount(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="下单时间" prop="orderTime" style="margin-top:12px;">
          <el-date-picker v-model="form.orderTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择下单时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="总金额">
          <el-input-number 
            v-model="form.sumAmount" 
            :min="0" 
            :precision="2" 
            :step="1" 
            style="width: 100%"
            @change="handleManualAmountChange"
          />
        </el-form-item>

        <el-divider>支付方式</el-divider>
        <el-form-item label="卡结算：账户余额">
          <el-input-number v-model="form.backPayment2" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="产品账户">
          <el-input-number v-model="form.payment2" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="现金支付">
          <el-input-number v-model="form.payment3" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="银行卡支付">
          <el-input-number v-model="form.payment4" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="挂账支付">
          <el-input-number v-model="form.payment5" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="免账支付">
          <el-input-number v-model="form.payment6" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="微信支付">
          <el-input-number v-model="form.payment7" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="支付宝支付">
          <el-input-number v-model="form.payment8" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="大众点评抵扣金额">
          <el-input-number v-model="form.payment9" :min="0" :precision="2" :step="1" />
        </el-form-item>

        <el-form-item label> </el-form-item>
        <el-form-item label="订单状态">
          <el-radio-group v-model="form.orderStatus">
            <el-radio label="未付款" value="00">未付款</el-radio>
            <el-radio label="已完成" value="02">已完成</el-radio>
            <el-radio label="挂账订单" value="03">挂账订单</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload action="#" :auto-upload="false">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传大小不超过 50MB 格式为 jpg/png/pdf 的文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderItemInfo">
import { ref, reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { parseTime } from '@/utils/ruoyi'
import { listShopItem } from '@/api/system/shopItem'
import { listGoodsinfo } from '@/api/system/goodsinfo'
import { listOrderItemInfo } from '@/api/system/orderiteminfo'
import request from '@/utils/request'
import { listUser } from '@/api/system/user'

const queryFormRef = ref()
const formRef = ref()
const state = reactive({
  loading: true,
  showSearch: true,
  total: 0,
  list: [],
  title: '',
  open: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    orderNo: undefined,
    orderBeginTime: undefined,
    orderEndTime: undefined,
  },
  form: {},
  rules: {
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    sumAmount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
    orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
    bindPhone: [
      { required: true, message: '请输入绑定手机号', trigger: 'blur' },
      { pattern: /^\d{11}$/, message: '手机号需为11位数字', trigger: ['blur', 'change'] }
    ]
  }
})

const { loading, showSearch, total, list, queryParams, title, open, form, rules } = toRefs(state)
const orderTimeRange = ref([])
const projectOptions = ref([])
const goodsOptions = ref([])

function getList() {
  loading.value = true
  listOrderItemInfo(queryParams.value).then(res => {
    list.value = res.rows || []
    total.value = res.total || 0
    loading.value = false
  }).catch(() => { loading.value = false })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  if (Array.isArray(orderTimeRange.value) && orderTimeRange.value.length === 2) {
    queryParams.value.orderBeginTime = orderTimeRange.value[0]
    queryParams.value.orderEndTime = orderTimeRange.value[1]
  } else {
    queryParams.value.orderBeginTime = undefined
    queryParams.value.orderEndTime = undefined
  }
  getList()
}

function resetQuery() {
  queryFormRef.value?.resetFields()
  orderTimeRange.value = []
  handleQuery()
}

function handleSelectionChange() {}

function indexMethod(index) {
  const p = queryParams.value || {}
  const pageNum = Number(p.pageNum || 1)
  const pageSize = Number(p.pageSize || 10)
  return (pageNum - 1) * pageSize + index + 1
}

function pick(row, keys) {
  for (const k of keys) {
    const v = row && row[k]
    if (v !== undefined && v !== null && v !== '') return v
  }
  return ''
}

// 表格合计行
function summaryMethod({ columns, data }) {
  const indexToField = {
    7: 'sumAmount',
    8: 'backPayment1',
    9: 'payment1',
    10: 'backPayment2',
    11: 'payment2',
    12: 'payment3',
    13: 'payment4',
    14: 'payment5',
    15: 'payment6',
    16: 'payment7',
    17: 'payment8',
    18: 'payment9',
    19: 'cardAmount'
  }
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const field = indexToField[index]
    if (field) {
      const total = (data || []).reduce((sum, row) => sum + (Number(row[field]) || 0), 0)
      sums[index] = total.toFixed(2)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

function resetForm() {
  form.value = {
    bindPhone: '',
    purchaserId: undefined,
    purchaserName: '',
    orderCode: '',
    items: [],
    products: [],
    orderTime: '',
    sumAmount: 0,
    // payments
    backPayment2: 0,
    payment2: 0,
    payment3: 0,
    payment4: 0,
    payment5: 0,
    payment6: 0,
    payment7: 0,
    payment8: 0,
    payment9: 0,
    orderStatus: '00',
    remark: ''
  }
  formRef.value?.resetFields()
}

function handleAdd() {
  resetForm()
  title.value = '新增项目订单'
  Promise.all([loadProjectOptions(), loadGoodsOptions()]).finally(() => { open.value = true })
}

function submitForm() {
  formRef.value?.validate(valid => {
    if (!valid) return
    // 占位：待接入新增接口
    open.value = false
    ElMessage.success('已提交，待接入新增接口')
  })
}

function cancel() {
  open.value = false
}

// 用户查询占位
const searchingUser = ref(false)
function onBindPhoneInput() {
  form.value.bindPhone = String(form.value.bindPhone || '').replace(/\D/g, '').slice(0, 11)
}
async function handleSearchUser() {
  const phone = String(form.value.bindPhone || '')
  if (!/^\d{11}$/.test(phone)) {
    ElMessage.warning('请先输入11位手机号')
    return
  }
  searchingUser.value = true
  try {
    // 优先以常见参数 phonenumber 查询；为兼容不同后端，附带多个可能的参数名
    const query = { phonenumber: phone, pageNum: 1, pageSize: 1 }
    const res = await listUser(query)
    const rows = res?.rows || []
    if (!rows.length) {
      form.value.purchaserId = undefined
      form.value.purchaserName = ''
      ElMessage.warning('未找到该手机号对应的用户')
      return
    }
    const u = rows[0]
    form.value.purchaserId = u.userId || u.id
    form.value.purchaserName = u.nickName || u.userName || u.realName || u.name || ''
    ElMessage.success('已匹配到绑定用户')
  } catch (e) {
    ElMessage.error('查询用户失败')
  } finally {
    searchingUser.value = false
  }
}

// 技师选项
const technicianOptions = ref([])
const loadingTechnicians = ref(false)

// 获取技师列表
const fetchConsultants = async () => {
  try {
    loadingTechnicians.value = true
    const res = await request({
      url: '/shop/itemconsultant/getAllConsultantlistCurrent',
      method: 'get'
    })
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      technicianOptions.value = res.rows.map(tech => ({
        value: tech.userId,
        label: tech.nickName || tech.userName || '未知技师'
      }))
    } else {
      // 如果返回的数据格式不同，尝试直接使用整个响应作为数组
      const data = res.data || res.rows || []
      if (Array.isArray(data)) {
        technicianOptions.value = data.map(tech => ({
          value: tech.userId || tech.id,
          label: tech.nickName || tech.userName || tech.name || '未知技师'
        }))
      }
    }
    
    // 确保始终有'其他'选项
    if (!technicianOptions.value.some(opt => opt.value === 'other')) {
      technicianOptions.value.push({ value: 'other', label: '其他' })
    }
  } catch (error) {
    console.error('获取技师列表失败:', error)
    ElMessage.error('获取技师列表失败')
    // 设置默认选项
    technicianOptions.value = [
      { value: 'other', label: '其他' }
    ]
  } finally {
    loadingTechnicians.value = false
  }
}

// 组件挂载时获取技师列表和产品列表
onMounted(() => {
  fetchConsultants();
  // 确保产品选项已加载
  loadGoodsOptions();
})

// 项目/产品行编辑与合计
let selectedItemRows = []
let selectedProductRows = []
function addItemRow() {
  form.value.items.push({ itemId: undefined, itemName: '', price: 0, qty: 1, cardRemain: 0, cardTimes: 0, technician: '' })
  calcTotals()
}
function removeSelectedItems() {
  form.value.items = form.value.items.filter(r => !selectedItemRows.includes(r))
  selectedItemRows = []
  calcTotals()
}
function addProductRow() {
  form.value.products.push({
    productId: '',
    productName: '',
    price: 0,
    qty: 0,
    finalAmount: 0,
    plan: ''
  })
  calcTotals()
}
function removeSelectedProducts() {
  form.value.products = form.value.products.filter(r => !selectedProductRows.includes(r))
  selectedProductRows = []
  calcTotals()
}
// 更新项目或产品的最终金额
function updateItemFinalAmount(row) {
  // 确保最终金额是数字且保留两位小数
  row.finalAmount = row.finalAmount !== null ? Number(Number(row.finalAmount).toFixed(2)) : 0;
  // 更新总金额
  updateTotalAmount();
}

// 更新总金额
function updateTotalAmount() {
  const itemTotal = (form.value.items || []).reduce((s, r) => {
    return s + (r.finalAmount !== undefined ? Number(r.finalAmount) : (Number(r.price)||0) * (Number(r.qty)||0));
  }, 0);
  
  const prodTotal = (form.value.products || []).reduce((s, r) => {
    return s + (r.finalAmount !== undefined ? Number(r.finalAmount) : (Number(r.price)||0) * (Number(r.qty)||0));
  }, 0);
  
  form.value.sumAmount = Number((itemTotal + prodTotal).toFixed(2));
}

function calcTotals(forceUpdate = false) {
  // 更新每个项目的最终金额（如果未手动设置）
  (form.value.items || []).forEach(item => {
    if (item.finalAmount === undefined || forceUpdate) {
      item.finalAmount = Number(((Number(item.price)||0) * (Number(item.qty)||0)).toFixed(2));
    }
  });
  
  // 更新每个产品的最终金额（如果未手动设置）
  (form.value.products || []).forEach(product => {
    if (product.finalAmount === undefined || forceUpdate) {
      product.finalAmount = Number(((Number(product.price)||0) * (Number(product.qty)||0)).toFixed(2));
    }
  });
  
  // 更新总金额
  updateTotalAmount();
}

// 处理手动修改总金额
function handleManualAmountChange(val) {
  // 确保金额是数字且保留两位小数
  form.value.sumAmount = val !== null ? Number(Number(val).toFixed(2)) : 0;
}

function loadProjectOptions() {
  return listShopItem({ pageNum: 1, pageSize: 999 }).then(res => {
    const rows = res?.rows || []
    projectOptions.value = rows.map(r => ({
      label: r.itemName || r.projectName || r.name,
      value: r.id,
      price: r.price || 0
    }))
  }).catch(() => { projectOptions.value = [] })
}

function onSelectItem(row, val) {
  const it = (projectOptions.value || []).find(o => String(o.value) === String(val))
  if (it) {
    row.itemName = it.label
    const newPrice = Number(it.price) || 0
    // Only update price if it's different to prevent unnecessary recalculations
    if (row.price !== newPrice) {
      row.price = newPrice
      // Set finalAmount to the calculated price * quantity
      row.finalAmount = Number((newPrice * (row.qty || 1)).toFixed(2))
    }
  } else {
    row.itemName = ''
    row.price = 0
    row.finalAmount = 0
  }
  // Always update totals when selection changes
  updateTotalAmount()
}

function loadGoodsOptions() {
  return listGoodsinfo({ pageNum: 1, pageSize: 999 }).then(res => {
    const rows = res?.rows || []
    goodsOptions.value = rows.map(r => ({
      label: r.goodsName || r.productName || r.name,
      value: r.id,
      price: r.price || 0
    }))
  }).catch(() => { goodsOptions.value = [] })
}

function onSelectProduct(row, val) {
  const it = (goodsOptions.value || []).find(o => String(o.value) === String(val));
  if (it) {
    row.productName = it.label;
    // 直接设置价格，不检查是否不同
    row.price = Number(it.price) || 0;
    
    // 设置初始数量为1（如果没有设置）
    if (!row.qty || row.qty === 0) {
      row.qty = 1;
    }
    
    // 计算最终金额
    row.finalAmount = Number((row.price * row.qty).toFixed(2));
    
    // 强制Vue更新视图
    row = Object.assign({}, row);
  } else {
    row.productName = '';
    row.price = 0;
    row.qty = 0;
    row.finalAmount = 0;
  }
  
  // 更新总金额
  updateTotalAmount();
}

// 增加划卡次数
function increment(row) {
  const newValue = (row.cardTimes || 0) + 1;
  updateCardTimes(row, newValue);
}

// 减少划卡次数
function decrement(row) {
  const newValue = Math.max(0, (row.cardTimes || 0) - 1);
  updateCardTimes(row, newValue);
}

// 处理划卡次数变化
function handleCardTimesChange(row, val) {
  // 确保划卡次数在有效范围内
  const maxCardTimes = row.cardRemain || 0;
  const newValue = Math.min(Math.max(0, Number(val) || 0), maxCardTimes);
  
  // 更新行数据
  row.cardTimes = newValue;
  
  // 同步更新数量
  row.qty = newValue;
  
  // 更新最终金额
  if (typeof row.price === 'number') {
    row.finalAmount = Number((row.price * row.qty).toFixed(2));
  }
  
  updateTotalAmount();
}

// 更新产品金额
function updateProductAmount(row) {
  if (typeof row.price === 'number' && typeof row.qty === 'number') {
    row.finalAmount = Number((row.price * row.qty).toFixed(2));
  } else {
    row.finalAmount = 0;
  }
  updateTotalAmount();
}

// 增加产品数量
function incrementQty(row) {
  row.qty = (row.qty || 0) + 1;
  updateProductAmount(row);
}

// 减少产品数量
function decrementQty(row) {
  row.qty = Math.max(0, (row.qty || 0) - 1);
  updateProductAmount(row);
}

// 更新划卡次数 (供+/-按钮使用)
function updateCardTimes(row, val) {
  row.cardTimes = val;
  handleCardTimesChange(row, val);
}

getList()
</script>
